package com.test.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by jl on 2018/8/13 0013
 * 测试executors的4种不同方式的线程池
 */
public class Demo {

    /**
     * 可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程
     */
    public static void cachedThdPoolTest() {
        ExecutorService cachedThdPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(i * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cachedThdPool.execute(() -> {
                System.out.println(index);
                System.out.println(Thread.currentThread());
            });
        }
    }

    /**
     * 定长线程池，可控制线程最大并发数，超出的线程会在队列中等待
     */
    public static void fixedThdPoolTest() {
        ExecutorService fixedThdPool = Executors.newFixedThreadPool(3);

    }

    /**
     * 定长线程池，支持定时及周期性任务执行
     */
    public static void scheduleThdPoolTest() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(new Runnable() {

            @Override
            public void run() {
                System.out.println("delay 3 seconds");
            }
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
     */
    public static void singleThdPoolTest() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println(index);
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public static void main(String[] args) {
        Thread thread = new Thread();
        thread.start();
    }
}
